package kinectKata.service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.StringTokenizer;

import javax.vecmath.Point3d;

import kinectData.models.DataReceiver;
import kinectData.models.ProjectSettings;

/**
 * Client connection to receive accelerometer data. 
 * 
 * @author Markus L�chtefeld (loechti)
 */
public class AccelerometerDataThread extends Thread {

	private DatagramSocket sensorSocketServer;	
	private DataReceiver controller;

	public AccelerometerDataThread(DataReceiver server) {
		this.controller = server;
	}

	public void run() {
		// A brute force method of trying to get the phone to connect to the default port.
		while (true) {
			try {
				sensorSocketServer = new DatagramSocket(ProjectSettings.ACCELEROMETER_PORT);
				while (true) {
					if (sensorSocketServer != null) {
						byte[] buf = new byte[512];
						DatagramPacket packet = new DatagramPacket(buf, buf.length);
						try {
							sensorSocketServer.receive(packet);
							buf = packet.getData();
							String data = new String(buf);
							StringTokenizer st = new StringTokenizer(data, "#");
							String deviceId = st.nextToken();
							// Make sure this is a device acceleration
							//if (deviceId.contains(":")) {									
								double x = Double.parseDouble(st.nextToken());
								double y = Double.parseDouble(st.nextToken());
								double z = Double.parseDouble(st.nextToken());
								controller.addSensorData(deviceId, 
									packet.getAddress().toString().substring(1), ProjectSettings.ACCELEROMETER_PORT, 
									new Point3d(x, y, z), data);
							//}
						} catch (IOException e) {
							System.err.println("Failed to receive packet from accel " + e.getMessage());
							e.printStackTrace();
						}
					}
				}
			} catch (Exception e) {
				System.err.println("Failed to connect to port " + ProjectSettings.ACCELEROMETER_PORT
					+ " " + e.getMessage());
				e.printStackTrace();
				sensorSocketServer = null;
				System.exit(1);
			}
		}
	}
}
